package pl.kosmowska.ewelina.client.app.activity;


import java.util.Date;
import java.util.List;

import pl.kosmowska.ewelina.client.Constants;
import pl.kosmowska.ewelina.client.ViewMessages;
import pl.kosmowska.ewelina.client.app.ClientFactory;
import pl.kosmowska.ewelina.client.app.activity.places.IncomePlace;
import pl.kosmowska.ewelina.client.app.activity.places.OutcomeEditPlace;
import pl.kosmowska.ewelina.client.app.activity.places.SignInPlace;
import pl.kosmowska.ewelina.client.app.requestfactory.dto.OutcomeDataProxy;
import pl.kosmowska.ewelina.client.app.user.AuthEvent;
import pl.kosmowska.ewelina.client.app.user.AuthEvent.Auth;
import pl.kosmowska.ewelina.client.app.user.AuthEventHandler;
import pl.kosmowska.ewelina.client.views.IncomeView;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.ServerFailure;

public class IncomeActivity extends AbstractActivity implements IncomeView.Presenter {

	private IncomeView view;

	private ClientFactory clientFactory;

	public IncomeActivity(IncomePlace place, ClientFactory clientFactory) {
		this.clientFactory = clientFactory;
	}

	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		view = clientFactory.getIncomeView();
		view.setPresenter(this);
		initAuthorisationForView();
		startView();
		containerWidget.setWidget(view.asWidget());
	}


	private void startView() {
		if (clientFactory.getIsLoggedIn() == null) {
			// wait for login event b/c hasn't happened yet
		} else if (clientFactory.getIsLoggedIn() == true) {
			loadDataForIncomeView();
		} else if (clientFactory.getIsLoggedIn() == false) { 
			goTo(new SignInPlace());
		}
	}

	public void goTo(Place place) {
		clientFactory.getPlaceController().goTo(place);
	}

	@Override
	public void goToNewIncomePlace() {
		clientFactory.getPlaceController().goTo(new OutcomeEditPlace(Constants.INCOME));
	}

	private void initAuthorisationForView() {
		if (view.isAlreadyInit() == false) {
			clientFactory.getEventBus().addHandler(AuthEvent.TYPE, new AuthEventHandler() {
				public void onAuthEvent(AuthEvent event) {
					Auth e = event.getAuthEvent();
					if (e == Auth.LOGGEDIN) {
						loadDataForIncomeView();
					} else if (e == Auth.LOGGEDOUT) {
						goTo(new SignInPlace());
					}
				}
			});
		}
		view.setAlreadyInit(true);
	}


	@Override
	public void loadDataForIncomeView(Date startDate, Date endDate) {
		clientFactory.getAppLoadingView().startProcessing();
		Request<List<OutcomeDataProxy>> req = clientFactory.getRequestFactory().getOutcomeDataRequest().findOutcomeDataByUserBetweenDates(false, startDate, endDate);
		req.fire(new Receiver<List<OutcomeDataProxy>>() {
			public void onSuccess(List<OutcomeDataProxy> returnedOutcomeData) {
				clientFactory.getAppLoadingView().stopProcessing();
				processIncomeList(returnedOutcomeData);
			}
			public void onFailure(ServerFailure error) {
				clientFactory.getAppLoadingView().stopProcessing();
				super.onFailure(error);
			}
		});

	}

	protected void processIncomeList(List<OutcomeDataProxy> returnedOutcomeData) {
		if (returnedOutcomeData == null || returnedOutcomeData.size() == 0) {
			view.showMessage(ViewMessages.NO_DATA_TO_SHOW);
			view.clearView();
		}else{
			view.reInitView( returnedOutcomeData);
		}

	}

	float round (float number){
		NumberFormat newFormat =NumberFormat.getFormat("#.##");
		return  Float.valueOf(newFormat.format(number));
	}

	@Override
	public void loadDataForIncomeView() {
		clientFactory.getAppLoadingView().startProcessing();
		Receiver<List<OutcomeDataProxy>> receiver= new Receiver<List<OutcomeDataProxy>>() {
			public void onSuccess(List<OutcomeDataProxy> returnedOutcomeData) {
				processIncomeList(returnedOutcomeData);
				clientFactory.getAppLoadingView().stopProcessing();
			}
			public void onFailure(ServerFailure error) {
				super.onFailure(error);
				clientFactory.getAppLoadingView().stopProcessing();
			}
		};
		Request<List<OutcomeDataProxy>> req = clientFactory.getRequestFactory().getOutcomeDataRequest().findOutcomeDataByUser(false,new Date());
		req.fire(receiver);

	}

	@Override
	public void deleteSingleIncome(final OutcomeDataProxy outcomeDataProxy) {
		Request<Boolean> req = clientFactory.getRequestFactory().getOutcomeDataRequest().deleteById(outcomeDataProxy.getId());
		req.fire(new Receiver<Boolean>() {
			public void onSuccess(Boolean data) {
				if (data != null && data.booleanValue() == true) {
					view.updateAfterIncomeDelete(outcomeDataProxy);

				} else {
					view.showMessage(ViewMessages.ERROR_ON_DELETE);
				}
			}
			public void onFailure(ServerFailure error) {
				super.onFailure(error);
			}
		});

	}

	@Override
	public void deleteFollowingMultipleIncome(OutcomeDataProxy outcomeDataProxy) {
		clientFactory.getRequestFactory().getOutcomeDataRequest().deleteRepeatedOutcomeData(outcomeDataProxy.getGroupKey(), outcomeDataProxy.getDate()).fire(new Receiver<List<OutcomeDataProxy>>() {
			public void onSuccess(List<OutcomeDataProxy> deletedList) {
				if (deletedList != null && !deletedList.isEmpty()) {
					view.updateAfterIncomeDelete(deletedList);

				} else {
					view.showMessage(ViewMessages.ERROR_ON_DELETE);
				}
			}
			public void onFailure(ServerFailure error) {
				super.onFailure(error);
			}
		}); 

	}

	@Override
	public void deleteAllMultipleIncome(OutcomeDataProxy outcomeDataProxy) {
		clientFactory.getRequestFactory().getOutcomeDataRequest().deleteRepeatedOutcomeData(outcomeDataProxy.getGroupKey(), null).fire(new Receiver<List<OutcomeDataProxy>>() {
			public void onSuccess(List<OutcomeDataProxy> deletedList) {
				if (deletedList != null && !deletedList.isEmpty()) {
					view.updateAfterIncomeDelete(deletedList);

				} else {
					view.showMessage(ViewMessages.ERROR_ON_DELETE);
				}
			}
			public void onFailure(ServerFailure error) {
				super.onFailure(error);
			}
		}); 
	}

	@Override
	public void goToIncomeeEditPlace(OutcomeDataProxy selectedItem) {
		OutcomeEditPlace place = new OutcomeEditPlace(selectedItem);
		goTo(place);
		
	}

}


